﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Model;
using System.Text.RegularExpressions;
using University.Workshop.DataAccess;
using System.Globalization;

namespace University.Workshop.Business
{
    public static class AuctionRegistrationManager
    {
        public static Auction RegisterAuction(String email,String initialAmount, String currency, String productId, DateTime date, int hour, int minutes)
        {
            if (String.IsNullOrEmpty(initialAmount) || String.IsNullOrEmpty(productId) || String.IsNullOrEmpty(email) || String.IsNullOrEmpty(currency))
            {
                throw new ValidationException("All fields are required");
            }
            if (hour < 0 || minutes < 0)
            {
                throw new ValidationException("Invalid Hour");
            }
            if (date.Date == DateTime.Now.Date)
            {
                if ((hour == DateTime.Now.Hour && minutes <= DateTime.Now.Minute) || (hour < DateTime.Now.Hour))
                {
                    throw new ValidationException("Invalid Time");
                }
            }
            if (date.Date < DateTime.Now.Date)//lo necesito
            {
                throw new ValidationException("Invalid Date");
            }
            
            string numbers = @"^[0-9.,]+$";
            if (!Regex.IsMatch(initialAmount, numbers))
            {
                throw new ValidationException("Invalid Amount");
            }
            
            Auction auction = new Auction();
            Product product = ProductDataAccess.GetProductById(Convert.ToInt64(productId,CultureInfo.CurrentCulture));
            product.Status = "OnAuction";
            auction.ProductId = Convert.ToInt64(productId, CultureInfo.CurrentCulture);
            auction.LastBidPrice = float.Parse(initialAmount, CultureInfo.CurrentCulture);
            auction.Currency = currency;
            String fechaHora = date.Month.ToString(CultureInfo.CurrentCulture)+"/"+date.Day.ToString(CultureInfo.CurrentCulture)+"/"+date.Year.ToString(CultureInfo.CurrentCulture)+ " " + hour.ToString(CultureInfo.CurrentCulture) + ":" + minutes.ToString(CultureInfo.CurrentCulture) + ":00";
            auction.Date = Convert.ToDateTime(fechaHora, CultureInfo.GetCultureInfo("en-US"));
            try
            {
                auction.BidderUserId=UserDataAccess.GetUserByEmail(email).Id;
                AuctionDataAccess.RegisterAuction(auction);
                ProductDataAccess.ModifyProduct(product);
                
            }
            catch (Exception ex)
            {
                throw new BusinessException("Error Insert Auction", ex);
            }
            return auction;
        }
    }
}
